package com.hp.process;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Scheduled;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.BlockingQueue;

public class QueueTaskService {


    @Autowired
    private MailSendQueueTask mailSendQueueTask;

    @Autowired
    private JavaMailSenderImpl mailSender;

    @Scheduled(cron = "10/2 * * * * ?")
    public synchronized void tack() {
//		System.out.println("开始检查队列，是否可以发送邮箱...");
        BlockingQueue<Map<String, Object>> queue = mailSendQueueTask.getQueue();
        if(queue.size()>0){
            System.out.println("对列长度："+queue.size());
            Map<String, Object> map = queue.poll();
            KeepAlive keepAlive = (KeepAlive) map.get("email");
            try {
                sendMail( "2564800708@qq.com","模块:"+keepAlive.getName()+",ID:"+keepAlive.getId()+"已掉线,请登录:http://localhost/tk/login.jsp 及时进行处理!");
            } catch (Exception e) {
                queue.offer(map);
            }

        }

    }

    /**
     * 发送邮箱
     * @param email
     * @throws Exception
     */
    public  void sendMail(String email,String code) throws Exception {
        System.out.println("发送邮箱......");
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom("maosuyu@foxmail.com","系统通知");//发件人
        helper.setTo(email);//收件人
        helper.setSentDate(new Date());
        helper.setSubject("系统掉线");
        helper.setText(code);
        mailSender.send(message);
    }
}
